package com.gift.recommendation.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzh <2658137258@qq.com>
 * @date 2022/11/3
 */
public class TokenConfig {
    //设置过期时间
    private static final long EXPIRE_DATE = 30*60*100000;
    //token密钥
    private static final String TOKEN_SECRET = "LJSBF932GFH9WF9WEGFFGWEPUFWPUFG3Q3D";

    /**
     * 创建token
     * @param uuid
     * @return
     */
    public static String createToken(String uuid){
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() +EXPIRE_DATE);
            //加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("token","test");
            token = JWT.create().withHeader(header).withClaim("uuid",uuid).withExpiresAt(date).sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return token;
    }

    /**
     * 验证密钥是否正确
     * @param token
     * @return
     */
    public static boolean verify(String token){
            Algorithm algorithm =Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
    }
}
